<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <!-- <a-button type="primary" @click="handleNormal" preIcon="ant-design:edit-outlined"> 激活</a-button> -->
        <a-button type="primary" @click="handlereportLost" preIcon="ant-design:edit-outlined"> 挂失</a-button>
        <a-button type="primary" @click="handlereleaseLost" preIcon="ant-design:edit-outlined"> 解挂</a-button>
        <a-button type="primary" @click="handlerbackcard" preIcon="ant-design:edit-outlined"> 退卡</a-button>
        <a-button type="primary" @click="handlerrecard" preIcon="ant-design:edit-outlined"> 补卡</a-button>
        <a-button type="primary" @click="handlercollect" preIcon="ant-design:edit-outlined"> 回收</a-button>
        <a-button  type="primary" preIcon="ant-design:export-outlined" @click="exportTemplateXls"> 下载导入模板</a-button>
          <a-button  type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button  type="primary" preIcon="ant-design:import-outlined" @click="onImportXls1">导入</j-upload-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button>批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <!--<super-query :config="superQueryConfig" @search="handleSuperQuery" />-->
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <SsCardModal @register="registerModal" @success="handleSuccess"></SsCardModal>
    <SsCardModalRecard @register="registerModalRecard" @success="handleSuccess"></SsCardModalRecard>

  </div>
</template>

<script lang="ts" name="baseinfo-ssCard" setup>
  import {ref, reactive, computed, unref} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import SsCardModal from './components/SsCardModal.vue'
  import SsCardModalRecard from './components/SsCardModalRecard.vue'
  const { handleExportXls, handleImportXls } = useMethods();
  import {columns, searchFormSchema, superQuerySchema} from './SsCard.data';
  import {
    list,
    deleteOne,
    batchDelete,
    getImportUrl,
    getExportUrl,
    normal,
    releaseLost,
    reportLost, backcard, recollect, getCardExportTemplateUrl
  } from './SsCard.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import {useMessage} from "@/hooks/web/useMessage";
  import {useMethods} from "@/hooks/system/useMethods";
  import {useGlobSetting} from "@/hooks/setting";
  import {defHttp} from "@/utils/http/axios";
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  const userStore = useUserStore();
  //注册model
  const [registerModal, {openModal}] = useModal();
  const [registerModalRecard, {openModal:openModalRecard}] = useModal();

  const { createMessage, createErrorModal,createWarningModal,createInfoModal } = useMessage();
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '卡',
           api: list,
           columns,
           canResize:false,
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
              fieldMapToTime: [
              ],
            },
           actionColumn: {
               width: 150,
               fixed:'right'
            },
            beforeFetch: (params) => {
              return Object.assign(params, queryParam);
            },
      },
       exportConfig: {
            name:"卡",
            url: getExportUrl,
            params: queryParam,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccessImport
          },
  })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
  async function handleNormal(){
    const select = rowSelection.selectedRows;
    if(select.length == 0){
      return createMessage.warn("请先选择数据")
    }
    await normal({ids: selectedRowKeys.value}, handleSuccess);
  }
  async function handlereleaseLost(){
      const select = rowSelection.selectedRows;
      if(select.length == 0){
        return createMessage.warn("请先选择数据")
      }
      await releaseLost({ids: selectedRowKeys.value}, handleSuccess);
    
  }
  async function handlerbackcard(){
    const select = rowSelection.selectedRows;
    if(select.length == 0){
      return createMessage.warn("请先选择数据")
    }
    await backcard({ids: selectedRowKeys.value}, handleSuccess);
   
   
  }
  async function handlerrecard() {
    const select = rowSelection.selectedRows;
    if(select.length != 1){
      return createMessage.warn("只能选择一张卡操作")
    }
    const record = select[0];
      openModalRecard(true, {
        record,
        isUpdate: true,
        showFooter: true,
      });
  }



  function exportTemplateXls() {
    let realUrl = getCardExportTemplateUrl ;
    return handleExportXls("卡片导入模板", realUrl, new Object());
  }


  async function handlercollect(){
    const select = rowSelection.selectedRows;
    if(select.length == 0){
      return createMessage.warn("请先选择数据"+`\n`+"test")
    }
    await recollect({ids: selectedRowKeys.value}, handleSuccess);
  }


  async function handlereportLost(){
    const select = rowSelection.selectedRows;
    if(select.length == 0){
      return createMessage.warn("请先选择数据")
    }
     await reportLost({ids: selectedRowKeys.value}, handleSuccess);
    
  }


  function handleSuccessImport(data){
    //if(data.indexOf(""))
    createInfoModal({
      title: '上传信息',
      content: '' + data,
      maskClosable: true,
    });
    (selectedRowKeys.value = []) && reload();

  }


  // 导入 excel
  function onImportXls1(file) {
    let { url, success } = {url: getImportUrl,
      success: handleSuccessImport};
    //update-begin-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
    let realUrl = typeof url === 'function' ? url() : url;
    if (realUrl) {
      return importXls11(file, realUrl, success || reload);
      //update-end-author:taoyan date:20220507 for: erp代码生成 子表 导入地址是动态的
    } else {
      $message.createMessage.warn('没有传递 importConfig.url 参数');
      return Promise.reject();
    }
  }

  const glob = useGlobSetting();
  /**
   * 导入xls
   * @param data 导入的数据
   * @param url
   * @param success 成功后的回调
   * createErrorModal({
            title: '上传出错',
            content: '错误信息：' + file['message'],
            maskClosable: true,
          });
   */
  async function importXls11(data, url, success) {
    const isReturn = (fileInfo) => {
      try {
        if (fileInfo.code === 201) {
          let {
            message,
            result: { msg, fileUrl, fileName },
          } = fileInfo;
          let href = glob.uploadUrl + fileUrl;
          createWarningModal({
            title: message,
            centered: false,
            content: `<div>
                                <span>${msg}</span><br/>
                                <span>具体详情请<a href = ${href} download = ${fileName}> 点击下载 </a> </span>
                              </div>`,
          });
          //update-begin---author:wangshuai ---date:20221121  for：[VUEN-2827]导入无权限，提示图标错误------------
        } else if (fileInfo.code === 500 || fileInfo.code === 510) {
          createMessage.error(fileInfo.message || `${data.file.name} 导入失败`);
          //update-end---author:wangshuai ---date:20221121  for：[VUEN-2827]导入无权限，提示图标错误------------
        } else {
          if(fileInfo.length==0)
          createMessage.success(fileInfo.message || `${data.file.name} 文件上传成功`);
        }
      } catch (error) {
        console.log('导入的数据异常', error);
      } finally {
        typeof success === 'function' ? success(fileInfo) : '';
      }
    };
    await defHttp.uploadFile({ url }, { file: data.file }, { success: isReturn });
  }

   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         }
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }, {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
             placement: 'topLeft',
           }
         }
       ]
   }





</script>

<style scoped>

</style>
